package com.cyanite.playlv2;

import com.cyanite.playlv2.interpolator.ExpoInterpolator;
import com.cyanite.playlv2.interpolator.EasingType.Type;
import com.cyanite.playlv2.util.NotificationsUtil;
import com.cyanite.playlv2.widget.Panel;
import com.cyanite.playlv2.widget.SecretListAdapter;
import com.cyanite.playlv2.widget.SegmentedButton;
import com.cyanite.playlv2.widget.Panel.OnPanelListener;
import com.cyanite.playlv2.widget.SegmentedButton.OnClickListenerSegmentedButton;
import com.cyanite.playlv2api.types.Group;
import com.cyanite.playlv2api.types.Response;
import com.cyanite.playlv2api.types.Secret;
import com.cyanite.playlv2api.util.ConstantsUtils;
import com.cyanite.playlv2api.util.ConstantsUtils.SecretLevelConsts;
import com.cyanite.playlv2api.util.ConstantsUtils.ShareSecretLevelConsts;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class SecretActivity extends Activity{

    private static final int ACTIVITY_REQUEST_PHOTO = 815;
    public static final String EXTRA_USER_ID = PlayLv2.PACKAGE_NAME
        + ".SecretActivity.EXTRA_USER_ID";

    private View mViewProgressBar;
    private ProgressDialog mDlgProgress;
    private StateHolder mStateHolder;
    private EditText mSecretText;
    private ImageView mSecretPhoto;
    private LinearLayout mllSecond;
    private Panel mPanel;
    private LinearLayout mEmpty;

    private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.secret_activity);
        registerReceiver(mLoggedOutReceiver, new IntentFilter(PlayLv2.INTENT_ACTION_LOGGED_OUT));

        mStateHolder = new StateHolder();
        if (getIntent().hasExtra(EXTRA_USER_ID))   {
            mStateHolder.setUserId(getIntent().getExtras().getString(EXTRA_USER_ID));
        }   else {
            finish();
            return;
        }

        mStateHolder.setIsLoggedInUser(
                mStateHolder.getUserId() == null ||
                mStateHolder.getUserId().equals(((PlayLv2) getApplication()).getUserId()));

        mViewProgressBar = findViewById(R.id.secretProgress);
        mViewProgressBar.setVisibility(View.VISIBLE);
        mStateHolder.startTaskGetHistorySecrets(this);

        ensureUi();
    }

    private void ensureUi() {
        setTitle(getString(R.string.secret_activity_title));

        TextView title = (TextView)findViewById(R.id.secretTitle);
        mllSecond = (LinearLayout)findViewById(R.id.llSecondlayer);
        mllSecond.getBackground().setAlpha(0);
        mllSecond.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                if (mStateHolder.getIsPanelOpen()) {
                    mPanel.setOpen(false, true);
                }
            }

        });
        mPanel = (Panel) findViewById(R.id.bottomPanel);
        mEmpty = (LinearLayout) findViewById(R.id.llEmptySecret);
        if (mStateHolder.getIsLoggedInUser())   {
            title.setText(getString(R.string.secret_activity_title_me_note));
            mSecretText = (EditText)findViewById(R.id.etSecretInfo);
            mSecretPhoto = (ImageView)findViewById(R.id.ivSecretPhoto);
            
            mPanel.setVisibility(View.VISIBLE);
            mPanel.setInterpolator(new ExpoInterpolator(Type.OUT));
            mPanel.setOnPanelListener(new OnPanelListener(){
                public void onPanelClosed(Panel panel) {
                    mllSecond.getBackground().setAlpha(0);
                    mStateHolder.setIsPanelOpen(false);
                    mSecretText.setText("");
                    mSecretPhoto.setImageBitmap(null);
                }
                public void onPanelOpened(Panel panel) {
                    mllSecond.getBackground().setAlpha(170);
                    mStateHolder.setIsPanelOpen(true);
                }
            });

            Button btnSetRight = (Button)findViewById(R.id.btnSetRight);
            btnSetRight.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    SecretFriendsDialog dlg = new SecretFriendsDialog(SecretActivity.this,
                            (PlayLv2)SecretActivity.this.getApplication(),
                            dataHandler);
                    dlg.show();
                }
            });
            Button btnCamera = (Button)findViewById(R.id.btnSecretCamera);
            btnCamera.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    if (mStateHolder.getSecret().getPhotoBmp() == null) {
                        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(cameraIntent, ACTIVITY_REQUEST_PHOTO);
                    }
                }
            });

            Button btnPublish = (Button)findViewById(R.id.btnPublishSecret);
            btnPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String text = mSecretText.getText().toString();
                if ( text.length() > 0 ){
                    mStateHolder.getSecret().setShout(text);
                }else{
                    Toast.makeText(SecretActivity.this, SecretActivity.this.getString(R.string.secret_empty), Toast.LENGTH_LONG);
                    return;
                }
                startProgressBar(getResources().getString(R.string.secret_label),
                        getResources().getString(R.string.secret_send_secrets_progress_message_post));
                mStateHolder.startTaskCreateSecret(SecretActivity.this);
                }
             });
        }   else    {
            title.setText(getString(R.string.secret_activity_title_ta_note));
            mPanel.setVisibility(View.GONE);
        }

        updateUi();
    }

    private void updateUi() {
        if (mStateHolder.getSecrets() != null ) {
            ListView secretList = (ListView)findViewById(R.id.lvSecretList);
            SecretListAdapter listAdapter = new SecretListAdapter(this, mStateHolder.getSecrets());
            secretList.setAdapter(listAdapter);
            secretList.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Secret secret = mStateHolder.getSecrets().get(position);
                    if ( mStateHolder.getIsLoggedInUser() ){
                        Intent intent = new Intent(SecretActivity.this, SecretFollowsActivity.class);
                        intent.putExtra(SecretFollowsActivity.EXTRA_SECRET_ID, secret.getId());
                        startActivity(intent);
                    }else{
                        startProgressBar(getResources().getString(R.string.secret_label),
                                getResources().getString(R.string.secret_get_opened_secrets_progress_message_request));
                        mStateHolder.startTaskOpenSecret(SecretActivity.this, secret);
                    }
                }
            });
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
           if (mStateHolder.getIsPanelOpen()) {
               mPanel.setOpen(false, true);
           }    else {
               finish();
           }
           return true;
        }
        else
            return super.onKeyDown(keyCode, event);
    }

    private void startProgressBar(String title, String message) {
        if (mDlgProgress == null) {
            mDlgProgress = ProgressDialog.show(this, title, message);
        }
        mDlgProgress.show();
    }

    private void stopProgressBar() {
        if (mDlgProgress != null) {
            mDlgProgress.dismiss();
            mDlgProgress = null;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
       switch ( requestCode ){
           case ACTIVITY_REQUEST_PHOTO:
               Bundle extras = data.getExtras();
               Bitmap bmp = (Bitmap) extras.get("data");
               mSecretPhoto.setImageBitmap(bmp);
               mSecretPhoto.setVisibility(View.VISIBLE);
               mStateHolder.getSecret().setPhotoBmp(bmp);
               break;
       }
    }

    private void onGetHistorySecretsTaskComplete(Group<Secret> secrets, Exception ex) {
        mViewProgressBar.setVisibility(View.GONE);
        if (secrets != null) {
            mStateHolder.setSecrets(secrets);
            updateUi();
            mEmpty.setVisibility(View.GONE);
        } else{
            mEmpty.setVisibility(View.VISIBLE);
        }
    }

    private static class GetHistorySecretsTask extends AsyncTask<Void, Void, Group<Secret>> {

        private SecretActivity mActivity;
        private Exception mReason;
        private String mUserId;

        public GetHistorySecretsTask(SecretActivity activity, String userId) {
            mActivity = activity;
            mUserId = userId;
        }

        @Override
        protected Group<Secret> doInBackground(Void... params) {
            try {
                return ((PlayLv2) mActivity.getApplication()).getPlayLv2Api().secrets(mUserId);
            } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute(Group<Secret> secrets) {
            if (mActivity != null) {
                mActivity.onGetHistorySecretsTaskComplete(secrets, mReason);
            }
        }

    }
    private SecretFriendsDialog.UserChoosedStatusHandler dataHandler = new SecretFriendsDialog.UserChoosedStatusHandler(){

        @Override
        public void onUsersChoosed(int secretLevel, String usersIdString) {
            mStateHolder.setSecretLevel(secretLevel);
            mStateHolder.setUsersIdString(usersIdString);
        }

    };
    private void onOpenSecretTaskComplete(Secret secret, Exception ex)   {
        stopProgressBar();
        if (secret != null) {
            SecretContentDialog dlg = new SecretContentDialog(this, secret);
            dlg.show();
        }
    }

    private static class OpenSecretTask extends AsyncTask<Void, Void, Secret> {

        private SecretActivity mActivity;
        private Exception mReason;
        private String mSecretId;

        public OpenSecretTask(SecretActivity activity, String secretId) {
            mActivity = activity;
            mSecretId = secretId;
        }

        @Override
        protected Secret doInBackground(Void... params) {
            try {
                return ((PlayLv2) mActivity.getApplication()).getPlayLv2Api().secret(mSecretId);
            } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute(Secret secret) {
            if (mActivity != null) {
                mActivity.onOpenSecretTaskComplete(secret, mReason);
            }
        }

        protected void onCancelled() {
            if (mActivity != null) {
                mActivity.onOpenSecretTaskComplete(null, new Exception(
                        "Get secret content cancelled."));
            }
        }
    }

    private void onCreateSecretTaskComplete(Response response, Exception ex) {
        stopProgressBar();
        if (response != null && response.getValue().equals("0")) {
            Toast.makeText(SecretActivity.this,
                    getResources().getString(R.string.secret_activity_set_ok),
                    Toast.LENGTH_LONG).show();
            if (mStateHolder.getIsPanelOpen()) {
                mPanel.setOpen(false, true);
            }
        } else {
            NotificationsUtil.ToastReasonForFailure(this, ex);
        }
    }

    private static class CreateSecretTask extends AsyncTask<Void, Void, Response> {

        private SecretActivity mActivity;
        private Exception mReason;
        private Secret mSecret;

        public CreateSecretTask(SecretActivity activity, Secret secret) {
            mActivity = activity;
            mSecret = secret;
        }

        @Override
        protected Response doInBackground(Void... params) {
            try {
                Location loc = ((PlayLv2)mActivity.getApplication()).getLastKnownLocation();
                if (loc == null) {
                    try {
                        Thread.sleep(ConstantsUtils.SLEEP_TIME_IF_NO_LOCATION);
                        } catch (InterruptedException ex) {}
                    loc = ((PlayLv2)mActivity.getApplication()).getLastKnownLocation();
                }
                if (loc != null)    {
                    mSecret.setLatitude(String.valueOf(loc.getLatitude()));
                    mSecret.setLongitude(String.valueOf(loc.getLongitude()));
                }
                //
                mSecret.setLatitude("30.65545");
                mSecret.setLongitude("104.077821");
                mSecret.setCost(2);
                if (mSecret.getSecretLevel() == SecretLevelConsts.SECRET_LEVEL_APPOINTED)  {

                }
                Response response = null;
                response = ((PlayLv2) mActivity.getApplication()).getPlayLv2Api().createSecret(
                        mSecret.getTitle(),
                        mSecret.getShout(),
                        mSecret.getPhotoId(),
                        mSecret.getLatitude(),
                        mSecret.getLongitude(),
                        String.valueOf(mSecret.getSecretLevel()),
                        String.valueOf(mSecret.getCost()),
                        mSecret.getUserIdsListString());
                if (response == null) response = new Response();
                return response;
            } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute(Response response) {
            if (mActivity != null) {
                mActivity.onCreateSecretTaskComplete(response, mReason);
            }
        }
    }

    private static class StateHolder {

        private boolean mIsLoggedInUser;
        private String mUserId;
        private Group<Secret> mSecrets;
        private GetHistorySecretsTask mGetSecretsHistoryTask;
        private OpenSecretTask mGetSecretContentTask;
        private CreateSecretTask mCreateSecretTask;
        private boolean mIsPanelOpen;
        private int mSecretLevel;
        private Secret mSecret;
        private String mUsersIdString;

        public StateHolder() {
            mIsLoggedInUser = false;
            mIsPanelOpen = false;
            mSecret = new Secret();
        }
        public void setUsersIdString(String usersId){
            mUsersIdString = usersId;
        }
        public boolean getIsLoggedInUser() {
            return mIsLoggedInUser;
        }

        public void setIsLoggedInUser(boolean isLoggedInUser) {
            mIsLoggedInUser = isLoggedInUser;
        }

        public Secret getSecret()   {
            return mSecret;
        }

        public boolean getIsPanelOpen() {
            return mIsPanelOpen;
        }

        public void setIsPanelOpen(boolean isOpen) {
            mIsPanelOpen = isOpen;
        }

        public String getUserId()   {
            return mUserId;
        }

        public void setUserId(String userId)    {
            mUserId = userId;
        }

        public int getSecretLevel(){
            return mSecretLevel;
        }

        public void setSecretLevel(int level)  {
            mSecretLevel = level;
        }

        public Group<Secret> getSecrets() {
            return mSecrets;
        }

        public void startTaskGetHistorySecrets(SecretActivity activity) {
            mGetSecretsHistoryTask = new GetHistorySecretsTask(activity, mUserId);
            mGetSecretsHistoryTask.execute();
        }

        public void startTaskOpenSecret(SecretActivity activity,Secret secret) {
            mGetSecretContentTask = new OpenSecretTask(activity, secret.getId());
            mGetSecretContentTask.execute();
        }

        public void startTaskCreateSecret(SecretActivity activity) {
            mSecret.setTitle("ben");
            mSecret.setUserIdsString(mUsersIdString);
            mSecret.setSecretLevel(mSecretLevel);
            mCreateSecretTask = new CreateSecretTask(activity, mSecret);
            mCreateSecretTask.execute();
        }

        public void setSecrets(Group<Secret> secrets) {
            mSecrets = secrets;
        }
    }
}
